

import 'dart:convert';
import 'dart:developer';

import 'package:dio/dio.dart';

class XinHeInterceptors extends InterceptorsWrapper {
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) async {
    // 添加请求头中的授权 token
    await _addAuthorizationHeader(options);

   log('====================接口请求====================' +
        '\n请求时间=>${DateTime.now()}' +
        '\n接口类型=>' +
        options.method +
        '\n接口路径=>' +
        options.path +
        '\n请求头headers' +
        options.headers.toString() +
        '\n接口参数（get）queryParameters=>' +
        options.queryParameters.toString()+
        '\n接口参数（post）data=>' +
        options.data.toString());

    super.onRequest(options, handler);
  }

  /// 添加授权 token 到请求头中
  Future<void> _addAuthorizationHeader(RequestOptions options) async {
    // final loginState = await KDLocalStorage.get(KDStorage.userLoginState);
    //
    // // 如果用户已登录，设置 token 和 uid 到请求头中
    // if (loginState is bool && loginState) {
    //   final accessToken = await KDLocalStorage.get(KDStorage.accessToken);
    //   if (accessToken != null) {
    //     options.headers["authorization"] = accessToken;
    //   }
    // }
  }


  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) async {
    final option = response.requestOptions;
    log('====================接口响应====================\n响应时间=>${DateTime.now()}\n接口类型=>${option.method}\n接口路径=>${option.path}\n接口参数（get）queryParameters=>${option.queryParameters}\n接口参数（post）data=>${option.data}${response.data}');
    try {
      // 判断是否需要解包
      final isUnpackRequired = _isUnpackRequired(option);
      if (isUnpackRequired) {
        return handler.resolve(response);
      }

      // 解析响应数据
      final dataObj = _parseResponseData(response);
      if (dataObj is List) {
        return handler.resolve(Response(data: dataObj, requestOptions: option));
      }

      // 处理返回结果带有 success 字段的情况
      if (dataObj is Map && dataObj.containsKey('success')) {
        final success = dataObj['success'];
        if (success == null || !success) {

          if (dataObj["code"] == 401) {
            // if (kdUserData.appLoginState.value){
            //   KDLocalStorage.set(KDStorage.userLoginState, false);
            //   //重置登录状态
            //   kdUserData.appLoginState.value = false;
            //   bus.emit(KDStorage.KdUserLogoutNot);
            // }
          }

          return handler.reject(DioError(
              requestOptions: option,
              response: Response(data: dataObj, requestOptions: option)));
        }
      }

      // 处理返回结果为空的情况
      if (dataObj.isEmpty) {
        return handler.reject(DioError(
            requestOptions: option,
            response: Response(data: '接口请求报错', requestOptions: option)));
      }

      // 请求成功
      return handler.resolve(Response(data: dataObj, requestOptions: option));
    } catch (e) {
      final errorMsg = e.toString();
      final errorResponse = Response(data: errorMsg, requestOptions: option);
      print(errorMsg + option.path);
      return handler.reject(DioError(
        requestOptions: option,
        response: errorResponse,
      ));
    }
  }

  /// 判断是否需要解包
  bool _isUnpackRequired(RequestOptions option) {
    final requestData = option.data;
    final queryParams = option.queryParameters;
    return (requestData != null && requestData['isUnpack'] == false) ||
        (queryParams.isNotEmpty && queryParams['isUnpack'] == false);
  }

  /// 解析响应数据
  dynamic _parseResponseData(Response response) {
    final responseData = response.data;

    if (responseData is Map) {
      return responseData;
    } else if (responseData.toString().contains("DOCTYPE html")) {
      throw DioError(
          requestOptions: response.requestOptions,
          response: Response(data: '接口数据异常', requestOptions: response.requestOptions));
    } else {
      return json.decode(responseData.toString()) ?? {};
    }
  }


  @override
  /// 错误处理函数
  void onError(DioError err, ErrorInterceptorHandler handler) {
    /// 获取错误信息并打印
    final errorInfo = _getErrorInfo(err);
    log(errorInfo);

    // TODO: 上传异常至服务器
    // TbrBuGly.uploadError(content: errorInfo);

    super.onError(err, handler);
  }

  /// 构建错误信息的辅助函数
  String _getErrorInfo(DioError err) {
    final requestOptions = err.requestOptions;
    final errMsg = err.message ?? '信息为空';
    final map = requestOptions.queryParameters;

    /// 构建错误信息字符串
    final error = '====================接口异常====================' +
        '\n请求时间=>${DateTime.now()}' +
        '\n接口类型=>' +
        requestOptions.method +
        '\n接口路径=>' +
        requestOptions.path +
        '\n异常参数=>' +
        map.toString() +
        '\n异常信息=>' +
        errMsg +
        '\n接口参数（get）queryParameters=>' +
        requestOptions.queryParameters.toString() +
        '\n接口参数（post）data=>' +
        requestOptions.data.toString();

    return error;
  }

}
